{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "64b28b77",
   "metadata": {},
   "source": [
    "# 百度AI开放平台\n",
    "## 通用物体和场景识别\n",
    "### 1、鉴权认证机制（获取access_token)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e3b2a3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials'\n",
    "    'client_id':\n",
    "    'client_secret':\n",
    "}\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2220c656",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.38e145573102769b76f4ae566833cfc1.315360000.1965013323.282335-25941681', 'expires_in': 2592000, 'session_key': '9mzdDoHN7WmsIs+omLmGsbZD17XCdE6zpjekm8oqUgKw8Q7bJtOYsrcFBBRHm9HcjnPt2AV5xm+6qgTKhh744b+NCpEQDQ==', 'access_token': '24.53093c098e10d67dfab505127380a13c.2592000.1652245323.282335-25941681', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '54cf76eeb164d6d54b2a11cf156c10cc'}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'mPFyGUwrqqFUSonhVXa09FXU',\n",
    "    'client_secret':'yAnEt0kFXoARulPVsk8U9iGMU2aYoAQS'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "62493551",
   "metadata": {},
   "outputs": [],
   "source": [
    "jiezhi_AT = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1387bb08",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cd2be925",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[             参数                                                  值\n",
       " 0  access_token  通过API Key和Secret Key获取的access_token,参考“Access ...,\n",
       "              参数                                  值\n",
       " 0  Content-Type  application/x-www-form-urlencoded,\n",
       "           参数       是否必选       类型 可选值范围  \\\n",
       " 0      image    和url二选一   string     -   \n",
       " 1        url  和image二选一   string     -   \n",
       " 2  baike_num          否  integer     -   \n",
       " \n",
       "                                                   说明  \n",
       " 0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       " 1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       " 2                                   返回百科信息的结果数，默认不返回  ,\n",
       "               字段 是否必选             类型                               说明\n",
       " 0         log_id    是         uint64                 唯一的log id，用于问题定位\n",
       " 1     result_num    是         unit32  返回结果数目，及result数组中的元素个数，最多返回5个结果\n",
       " 2         result    是  arrry(object)                           标签结果数组\n",
       " 3       +keyword    是         string                      图片中的物体或场景名称\n",
       " 4         +score    是          float                          置信度，0-1\n",
       " 5          +root    是         string   识别结果的上层标签，有部分钱币、动漫、烟酒等tag无上层标签\n",
       " 6    +baike_info    否         object                    对应识别结果的百科词条名称\n",
       " 7    ++baike_url    否         string                   对应识别结果百度百科页面链接\n",
       " 8    ++image_url    否         string                     对应识别结果百科图片链接\n",
       " 9  ++description    否         string                     对应识别结果百科内容描述]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 图像识别 url ： https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "223fe263",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '湖泊', 'score': 0.853226, 'root': '自然风景-湖泊', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B9%96%E6%B3%8A/242936', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/8435e5dde71190ef635cd56ccd1b9d16fcfa60d9', 'description': '湖盆及其承纳的水体。湖盆是地表相对封闭可蓄水的天然洼池。湖泊按成因可分为构造湖、火山口湖、冰川湖、堰塞湖、喀斯特湖、河成湖、风成湖、海成湖和人工湖(水库)等。按泄水情况可分为外流湖(吞吐湖)和内陆湖；按湖水含盐度可分为淡水湖(含盐度小于1g/L)、咸水湖(含盐度为1-35g/L)和盐湖(含盐度大于35g/L)。湖水的来源是降水、地面径流、地下水，有的则来自冰雪融水。湖水的消耗主要是蒸发、渗漏、排泄和开发利用。'}}, {'keyword': '江河', 'score': 0.672854, 'root': '自然风景-江河', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B1%9F%E6%B2%B3/9571871', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/4034970a304e251f9b897931a686c9177e3e53f8', 'description': '江河，男，原名于友泽，1949年生，北京人，1968年高中毕业。1980年5月在《上海文学》发表处女作《星星变奏曲》，著有诗集《从这里开始》《太阳和它的反光》等，是新时期朦胧诗派的代表诗人之一。他的诗作中灌注了相当厚重的历史感，以《纪念碑》等政治抒情诗和古代神话组诗《太阳和它的反光》赢得社会瞩目。与顾城、北岛、舒婷,杨炼一起并称为“五大朦胧诗人”。'}}, {'keyword': '桥梁', 'score': 0.422821, 'root': '建筑-现代建筑', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%A1%A5%E6%A2%81/2054921', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/ae51f3deb48f8c54c5bbc8c630292df5e1fe7fea', 'description': '桥梁，一般指架设在江河湖海上，使车辆行人等能顺利通行的构筑物。为适应现代高速发展的交通行业，桥梁亦引申为跨越山涧、不良地质或满足其他交通需要而架设的使通行更加便捷的建筑物。桥梁一般由上部构造、下部结构、支座和附属构造物组成，上部结构又称桥跨结构，是跨越障碍的主要结构；下部结构包括桥台、桥墩和基础；支座为桥跨结构与桥墩或桥台的支承处所设置的传力装置；附属构造物则指桥头搭板、锥形护坡、护岸、导流工程等。'}}, {'keyword': '自然公园', 'score': 0.247641, 'root': '自然风景-自然公园', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%87%AA%E7%84%B6%E5%85%AC%E5%9B%AD/6612051', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/810a19d8bc3eb135754be38aa11ea8d3fd1f4476', 'description': '《自然公园》是一款Android平台的应用。'}}, {'keyword': '天空', 'score': 0.065228, 'root': '自然风景-天空', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%A4%A9%E7%A9%BA/5534', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/241f95cad1c8a7868fa019076909c93d70cf5034', 'description': '天空，汉语词汇，拼音tiān kōng，谓天际空阔；日月星辰罗列的广大空间。是地球重要的组成部分，在古代中国有天圆地方的说法。人可以在天空观测气象或天文现象，从而得知天气变化、时间的流逝或自己的方位。日出日落可知一日中的时间，晚上月亮的盈亏可以知道一个月的时间。北斗星可以指示北方。云的厚度和形状可以知道会否下雨。 在天空可以欣赏到许多美丽的现象，如彩虹、极光和流星雨等。雀鸟会在天空飞翔。 由于石油等化石性燃料使用的增加而产生的悬浮质，特别是那些会在燃烧后释放二氧化硫的煤等燃料的影响，自1973年以来，除了欧洲，天空的能见度正在逐步降低。'}}], 'log_id': 1513382377276070948}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('xihu.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiezhi_AT,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "04ede375",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '283', 'has_calorie': True, 'name': '东坡肘子', 'probability': '0.839326', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E4%B8%9C%E5%9D%A1%E8%82%98%E5%AD%90/327468', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/060828381f30e92406bdf89540086e061d95f77d', 'description': '东坡肘子，四川省眉山市特产，国家地理标志产品。东坡肘子具有汤汁乳白，猪肘烂软，肉质细嫩、肉味醇香、有嚼头，肥而不腻等优点。2013年12月，东坡肘子成功获批国家地理标志保护产品称号。'}}, {'calorie': '227', 'has_calorie': True, 'name': '红烧肉', 'probability': '0.154128', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BA%A2%E7%83%A7%E8%82%89/571767', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/f31fbe096b63f624c51a87b68944ebf81b4ca3c4', 'description': '红烧肉(拼音： hóng shāo ròu、注音：ㄏㄨㄥˊ ㄕㄠ ㄖㄡˋ)，一道著名的大众菜肴，各大菜系都有自己特色的红烧肉。其以五花肉为制作主料，最好选用肥瘦相间的三层肉(五花肉)来做，锅具以砂锅为主，做出来的肉肥瘦相间，香甜松软，营养丰富，入口即化。红烧肉在我国各地流传甚广，做法多达二三十种，具有一定的营养价值。'}}, {'calorie': '549', 'has_calorie': True, 'name': '酱汁肉', 'probability': '0.00228836', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%85%B1%E6%B1%81%E8%82%89/3239542', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/4afbfbedab64034f68f9142aadc379310a551de1', 'description': '酱汁肉，是江苏省苏州市的传统名菜，卤酱菜谱之一。其特色是上口酥润，香味浓郁，皮糯肉烂,入口即化，肥而不腻，而色泽鲜艳。制作时猪蹄筋为主料。酱汁肉的烹饪技巧以酱菜为主，口味属于五香味。'}}, {'calorie': '463', 'has_calorie': True, 'name': '梅干菜扣肉', 'probability': '0.000681924', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%A2%85%E5%B9%B2%E8%8F%9C%E6%89%A3%E8%82%89/1947121', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/6a63f6246b600c33874425927807460fd9f9d72a0b1f', 'description': '梅干菜扣肉是传统特色菜肴，用连皮五花肉烧好后，再在碗里放上腌制的梅干菜，这样梅干菜扣肉就好了。'}}, {'has_calorie': False, 'name': '金牌坛香肉', 'probability': '0.000430435', 'baike_info': {}}], 'log_id': 1513383657052170400}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('dp.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "\n",
    "access_token = jiezhi_AT\n",
    "payload={\n",
    "    'access_token':jiezhi_AT,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "09a7915d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'name': '龙眼', 'score': 0.7813146, 'baike_info': {}}, {'name': '黄皮', 'score': 0.20164216, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%BB%84%E7%9A%AE/754109', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/a8014c086e061d95ef3434a17ef40ad162d9ca3d', 'description': '黄皮(学名：Clausena lansium (Lour.)Skeels)芸香科，小乔木，高可达12米。小叶卵形或卵状椭圆形，两侧不对称，圆锥花序顶生；花蕾圆球形，花萼裂片阔卵形，花瓣长圆形，花丝线状，果淡黄至暗黄色，果肉乳白色，半透明，种子1-4粒；4-5月开花，7-8月结果。中国海南的花果期均提早1-2个月。黄皮产于中国南方，距今已有一千五百多年的历史了。黄皮是中国南方果品之一，含丰富的维生素C、糖、有机酸及果胶，果皮及果核皆可入药，有消食化痰、理气功效，用于食积不化、胸膈满痛、痰饮咳喘等症，并可解郁热，理疝痛，叶性味辛凉，有疏风解表，除痰行气功效，用于防治流行性感冒、温病身热、咳嗽哮喘、水胀腹痛、疟疾、小便不利、热毒疥癞等症；根可治气痛及疝痛。(概述图参考：中国植物图像库)'}}, {'name': '荔枝', 'score': 0.024213728, 'baike_info': {}}, {'name': '无患子', 'score': 0.0021328467, 'baike_info': {}}, {'name': '龙荔', 'score': 0.0019957472, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%BE%99%E8%8D%94/8866179', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b999a9014c086e06ea0e11cb0f087bf40bd1cb88', 'description': '龙荔(学名：Dimocarpus confinis (How et Ho) H.S.Lo)是一种无患子科龙眼属植物，常绿大乔木，高可达20余米，胸高直径可达1米余；小枝粗壮，有5条明显的沟槽，干时草黄色，近无毛。叶连柄长35-50厘米或更长，叶轴圆柱状，有不甚明显的直线纹，常散生皮孔。花序顶生和腋生，直立，与叶近等长，主轴和分枝均有沟槽，密被绒毛；花柱稍粗短。核果卵圆形，长2-2.3厘米；种子红褐色，全部被肉质假种皮包裹。花期夏季，果期夏末秋初。分布于中国云南南部、贵州南部、广西、广东西部和湖南西南部；越南北部也有分布。生长于海拔400-1000米的阔叶林中。树干粗大，心材茶褐色，质坚而重，颇耐腐，据广西龙州等地群众反映是一种上等硬木，供建筑、制家具和砧板等用；假种皮有甜味，种子含淀粉，但有毒，未经处理，不可食，过致死。(概述图参考来源：)'}}], 'log_id': 1513384257412209994}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('ly.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\n",
    "    'access_token':jiezhi_AT,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1128033c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
